<?php

class Classes extends Eloquent {

    protected $table    = 'classes';
    protected $fillable = array ( 'course', 'team', 'level', 'crew', 'location', 'note', 'updater' );

    public function user() {
        return $this->belongsToMany('User', 'user_class', 'class_id', 'user_id')->withTimestamps()->withPivot('id', 'chuyencan', 'hocluc', 'rank', 'note', 'updater');
    }

    public function updater() {
        return $this->belongsTo('User', 'user_id')->withTimestamps();
    }

    public function generateClassName($bHideCourse = false) {

        $Options = Cache::get('options');

        $this->team  = isset($Options['NGANH'][$this->team]) ? $Options['NGANH'][$this->team]->data : $this->team;
        $this->level = isset($Options['CAP'][$this->level]) ? $Options['CAP'][$this->level]->data : $this->level;
        $this->crew  = isset($Options['DOI'][$this->crew]) ? $Options['DOI'][$this->crew]->data : $this->crew;

        $sName = $bHideCourse ? null : trans('classes.course') . " $this->course";
        $sTemp = $this->team ? trans('classes.team') . ' ' . $this->team : null;
        $sName = $sName && $sTemp ? $sName . ' - ' . $sTemp : $sName . $sTemp;
        $sTemp = $this->level ? trans('classes.level') . ' ' . $this->level : null;
        $sName = $sName && $sTemp ? $sName . ' - ' . $sTemp : $sName . $sTemp;
        $sTemp = $this->crew ? trans('classes.crew') . ' ' . $this->crew : null;
        $sName = $sName && $sTemp ? $sName . ' - ' . $sTemp : $sName . $sTemp;

        return $sName;
    }

    /**
     * Calculate ChuyenCan
     * @param string $sUser_ID
     * @param int $iCourse
     * @param int $iClass_ID
     * @return $iMinus 
     */
    public static function ChuyenCan($sUser_ID, $iCourse = null, $iClass_ID = null) {

        // <editor-fold defaultstate="collapsed" desc="Get UserClass and Class ID">
        if (!$iClass_ID) {
            if (!$iCourse)
                $iCourse = CNamHoa::CurrentCourse();

            $iClass_ID = Classes::where('course', $iCourse)->lists('id');
            $UserClass = User::find($sUser_ID)->classes()->whereIn('class_id', $iClass_ID)->first();
            $iClass_ID = $UserClass->pivot->class_id;
        } else {
            $UserClass = User::find($sUser_ID)->classes()->where('class_id', $iClass_ID)->first();
        }
        // </editor-fold>

        $iCourse = $UserClass->course;
        $Option  = Cache::get('options');

        $UserScore = UserScore::chuyencan([
                'start' => $Option['COURSE'][$iCourse]->data->start,
                'end'   => $Option['COURSE'][$iCourse]->data->end,
                ], $sUser_ID)->get();

        $iMinus = 0;

        foreach ($UserScore as $Object) {
            $iMinus += (float) $Object->data;
        }

        $UserClass->pivot->chuyencan = 10 + $iMinus;
        $UserClass->pivot->save();

        Classes::SetRank($iClass_ID);

        return $iMinus;
    }

    /**
     * Calculate HocLuc
     * @param string $sUser_ID
     * @param int $iCourse
     * @param int $iClass_ID
     * @return $iScore 
     */
    public static function HocLuc($sUser_ID, $iCourse = null, $iClass_ID = null) {

        // <editor-fold defaultstate="collapsed" desc="Get UserClass and Class ID">
        if (!$iClass_ID) {
            if (!$iCourse)
                $iCourse = CNamHoa::CurrentCourse();

            $iClass_ID = Classes::where('course', $iCourse)->lists('id');
            $UserClass = User::find($sUser_ID)->classes()->whereIn('class_id', $iClass_ID)->first();
            $iClass_ID = $UserClass->pivot->class_id;
        } else {
            $UserClass = User::find($sUser_ID)->classes()->where('class_id', $iClass_ID)->first();
        }
        // </editor-fold>

        $UserScore = UserScore::hocluc($sUser_ID)->get();

        $iScore = [ ];

        foreach ($UserScore as $Object) {
            $iScore[$Object->scoretype][$Object->data] = (float) $Object->score;
        }

        foreach ($iScore as $key => $value) {
            $iScore[$key] = array_sum($value) / count($value);
        }

        $iScore = array_sum($iScore) / count($iScore);

        $UserClass->pivot->hocluc = $iScore;
        $UserClass->pivot->save();

        Classes::SetRank($iClass_ID);

        return $iScore;
    }

    /**
     * Calculate HocLuc
     * @param string $sUser_ID
     * @param int $iCourse
     * @param int $iClass_ID
     */
    public static function SetRank($iClass_ID = null) {

        $UserClass = Classes::find($iClass_ID)->user()->thieunhi()->get();

        $aRank = [ ];

        foreach ($UserClass as $Object) {
            $Object = $Object->pivot;
            if ($Object->chuyencan < 5 || $Object->hocluc < 5) {
                $Object->rank = 'O_LAI';
            } else if ($Object->chuyencan >= 9 && $Object->hocluc >= 8) {
                $Object->rank = 'KHUYEN_KHICH';

                $aRank[$Object->user_id] = $Object->chuyencan + $Object->hocluc;

                if ($Object->chuyencan > $Object->hocluc) {
                    $aRank[$Object->user_id] += 0.000001;
                }
            } else {
                $Object->rank = 'LEN_LOP';
            }

            $Object->save();
        }

        asort($aRank);

        $aRank = array_reverse($aRank, true);
        $aRank = array_slice($aRank, 0, 3, true);

        foreach ($aRank as $UserId => $value) {

            foreach ($UserClass as $Object) {
                $Object = $Object->pivot;

                if ($Object->user_id == $UserId) {

                    switch (count($aRank)) {
                        case 3:
                            $Object->rank = 'HANG_I';
                            break;
                        case 2:
                            $Object->rank = 'HANG_II';
                            break;

                        default:
                            $Object->rank = 'HANG_III';
                            break;
                    }

                    array_pop($aRank);
                    $Object->save();
                    break;
                }
            }
        }
    }

}